# -*- coding: utf-8 -*-
#
###
#
# Copyright (C) 2009 yed_ <yed (a) vanyli (o) net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
###

import gtk, sys, os, time, gobject
from gtk.glade import XML as glade_XML
from pyfuploader.core import PyfuploadCore
from pyfuploader.trayicon import TrayIcon
from gettext import gettext as _
class PyfuploadGTK(PyfuploadCore):

  _glade = 'window.glade'

  def __init__(self):
    PyfuploadCore.__init__(self)
    self._init_windows()
    self._choose_default()

  def _init_windows(self):
    cwd = os.path.dirname( os.path.realpath( __file__ ) )
    self._wtree = glade_XML(os.path.join(cwd, self._glade))

    self._init_tray()
    self._init_main()
    self._init_menu()
    self._init_choose()
    self._init_conf()

  def _init_tray(self):
    self._icon = TrayIcon(self)

  def _init_menu(self):
    wdgt_exit = self._wtree.get_widget('menuitem_exit')
    wdgt_exit.connect('activate', lambda xt: gtk.main_quit())

  def _init_main(self):
    ''' input target '''
    self._inp_target = self._wtree.get_widget('inp_target')

    ''' main window '''
    self._main_window = self._wtree.get_widget('window_main')
    self._main_window.set_title(' '.join(PyfuploadCore.print_version()))
    self._main_window.connect("destroy", self.toggle_window)
    self._main_window.connect("delete-event", self.stop_delete)
    self._main_window.show_all()

    self._btn_upload = self._wtree.get_widget('btn_upload')
    self._btn_upload.connect('clicked', self.do_upload)
    self._btn_upload.set_label( _("Upload") )

    self._btn_choose = self._wtree.get_widget('btn_choose')
    self._btn_choose.connect("clicked", self.choose_dialog)
    self._btn_choose.set_label( _("Choose file for upload...") )
    self._btn_upload.set_sensitive(False)

    self._buffer_debug = gtk.TextBuffer()
    self._txt_debug = self._wtree.get_widget('txt_debug')
    self._txt_debug.set_buffer(self._buffer_debug)

    self._pbar_up = self._wtree.get_widget('progress_upload')

  ''' fileChooser dialog window'''
  def _init_choose(self):
    self._choose_window = self._wtree.get_widget("window_choose")
    self._choose_window.set_transient_for(self._main_window)

    cancel = self._wtree.get_widget('btn_cancel')
    cancel.connect("clicked", lambda cls: self._choose_window.hide())

    open = self._wtree.get_widget('btn_open')
    open.connect("clicked", self.proceed_file)

  ''' init connection '''
  def _init_conf(self):
    self._model_conn = gtk.ListStore(str)

    cell_conn = gtk.CellRendererText()
    col_conn = gtk.TreeViewColumn( _("Connection") )
    col_conn.pack_start(cell_conn)
    col_conn.set_attributes(cell_conn, text=0)

    self._list_conn = self._wtree.get_widget('list_conn')
    self._list_conn.connect('row-activated', self.conn_changed)
    self._list_conn.set_model(self._model_conn)
    self._list_conn.append_column(col_conn)

    for one in self.connections:
      self._model_conn.append([one])

    ''' server-side directories for each connection '''
    cell_dir = gtk.CellRendererText()
    col_conn = gtk.TreeViewColumn( _("Directory") )
    col_conn.pack_start(cell_dir)
    col_conn.set_attributes(cell_dir, text=0)

    self._model_dir = gtk.ListStore(str)

    self._list_dir  = self._wtree.get_widget('list_dir')
    self._list_dir.connect('row-activated', self.dir_changed)
    self._list_dir.set_model(self._model_dir)
    self._list_dir.append_column(col_conn)

  ''' handles change event for connection listbox '''
  def conn_changed(self, treeview, iter, col):
    iter_val = self._model_conn.get_iter(iter)
    conn_name = self._model_conn.get_value(iter_val, 0)

    self.set_connection(conn_name)

    self._model_dir.clear()
    conn_dirs = self.conn_dirs[conn_name]
    for name in conn_dirs:
      self._model_dir.append([name])

    if len(conn_dirs) > 0:
      self._list_dir.set_cursor((0,))
      self._list_dir.row_activated((0,0), self._list_dir.get_column(0))

  ''' handles change event for server-side directories '''
  def dir_changed(self, treeview, iter, col):
    iter_val = self._model_dir.get_iter(iter)
    dir_name = self._model_dir.get_value(iter_val, 0)
    
    self.set_directory(dir_name)
    self.set_target()
    
  ''' handler for file uploading event '''
  def proceed_file(self, wdgt):
    choosen_file = self._choose_window.get_filename()

    self._choose_window.hide()
    self._btn_upload.set_sensitive(True)
    self._btn_choose.set_label(os.path.basename(choosen_file))
    self.set_source(choosen_file)
    self.set_target()

  ''' init handler for choosing defaults (conn. and dir). TODO'''
  def _choose_default(self):
    iter = 0
    for one in self.connections:
      if self.default_connection == one:
        self._list_conn.set_cursor((iter,))
        self._list_conn.row_activated((iter,), self._list_conn.get_column(0))
        break
      iter += 1

  def choose_dialog(self, wdgt):
    self._choose_window.show_all()

  def progress(self, download_t, download_d, upload_t, upload_d):
    gtk.gdk.threads_enter()
    self._pbar_up.set_fraction(float(upload_d) / float(upload_t))
    gtk.gdk.threads_leave()

  def debug_output(self, lvl, msg):
    if lvl == 1:
      #print msg
      start, end = self._buffer_debug.get_bounds()
      gtk.gdk.threads_enter()
      self._buffer_debug.insert(end, msg)
      gtk.gdk.threads_leave()

  def set_connection(self, conn_name):
    try:
      self.choosen_connection = conn_name
    except:
      self.debug_output(1, _("Choosen connection does not exists") )

  def set_directory(self, dir_name):
    try:
      #self.choosen_directory = self.conn_dirs[self.choosen_connection][dir_name]
      self.choosen_directory = dir_name
    except:
      self.debug_output(1, _("Choosen directory does not exists") )

  def set_target(self):
    PyfuploadCore.set_target(self)
    if (self.target.has_key('url')):
      self._inp_target.set_text(self.target['url'])

  def post_upload(self):
    self._btn_upload.set_sensitive(True)

  def do_upload(self, wdgt):
    self._btn_upload.set_sensitive(False)
    try:
      self._init_slave()
      self._slave.start()
      #print 'umri ty osklive vlakenko!'

    except Exception, inst:
      self.debug_output(1, inst.message)
      self.post_upload()

  ''' @todo
    init handler for choosing defaults (conn. and dir)
  '''
  def set_default(self):
    iter = 0
    for one in self.connections:
      if self.default_connection == one:
        self._list_conn.set_cursor((iter, ))
        self._list_conn.row_activated((iter, ), self._list_conn.get_column(0))
        break
      iter += 1

  def toggle_window(self, wdgt=None):
    if self._main_window.is_active():
      self._win_position = self._main_window.get_position()
      self._main_window.hide()
    else:
      self._main_window.move(self._win_position[0], self._win_position[1])
      self._main_window.show()

    return True

  def stop_delete(self, wdgt, data):
    self._win_position = self._main_window.get_position()
    self._main_window.hide()

    return True
